import React, { useState } from 'react';
import { Form, Input, Button, Typography, Card, App } from 'antd';
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons';
import axios from 'axios';

const { Title } = Typography;

const SecuritySettings: React.FC = () => {
    const { message } = App.useApp();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [passwordMatch, setPasswordMatch] = useState<'none' | 'match' | 'mismatch'>('none');

    // Check password match when form values change
    const checkPasswordMatch = () => {
        // 使用setTimeout来避免过于频繁的检查
        setTimeout(() => {
            const newPassword = form.getFieldValue('newPassword');
            const confirmPassword = form.getFieldValue('confirmPassword');

            if (!confirmPassword) {
                setPasswordMatch('none');
            } else if (newPassword === confirmPassword) {
                setPasswordMatch('match');
            } else {
                setPasswordMatch('mismatch');
            }
        }, 100);
    };

    // Render password match indicator
    const renderPasswordMatchIcon = () => {
        switch (passwordMatch) {
            case 'match':
                return (
                    <CheckCircleOutlined
                        style={{
                            color: '#52c41a',
                            fontSize: '18px',
                            transition: 'all 0.3s ease'
                        }}
                        title="密码匹配"
                    />
                );
            case 'mismatch':
                return (
                    <CloseCircleOutlined
                        style={{
                            color: '#ff4d4f',
                            fontSize: '18px',
                            transition: 'all 0.3s ease'
                        }}
                        title="密码不匹配"
                    />
                );
            default:
                return null;
        }
    };

    // Handle password change form submission
    const onFinish = async (values: any) => {
        const token = localStorage.getItem('authToken');
        if (!token) {
            message.error('请先登录');
            return;
        }

        setLoading(true);

        try {
            await axios.post('/api/auth/change-password/', {
                current_password: values.currentPassword,
                new_password: values.newPassword
            }, {
                headers: { 'Authorization': `Token ${token}` }
            });

            message.success('密码修改成功！');
            form.resetFields();
            setPasswordMatch('none'); // 重置密码匹配状态
        } catch (error: any) {
            const errorMessage = error.response?.data?.error ||
                                error.response?.data?.current_password?.[0] ||
                                error.response?.data?.new_password?.[0] ||
                                '密码修改失败，请重试';
            message.error(errorMessage);
            console.error('Password change error:', error);
        } finally {
            setLoading(false);
        }
    };

    return (
        <div>
            <Title level={3}>安全设置</Title>
            <Card>
                <Title level={5}>修改密码</Title>
                <Form
                    form={form}
                    name="security"
                    layout="vertical"
                    onFinish={onFinish}
                    style={{ maxWidth: 400 }}
                >
                    <Form.Item
                        label="当前密码"
                        name="currentPassword"
                        rules={[{ required: true, message: '请输入你当前的密码!' }]}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            width: '100%'
                        }}>
                            <Input.Password
                                style={{
                                    width: 'calc(100% - 32px)',
                                    marginRight: '8px'
                                }}
                            />
                            <div style={{
                                width: '24px',
                                height: '32px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                flexShrink: 0
                            }}>
                                {/* 占位空间，保持布局一致 */}
                            </div>
                        </div>
                    </Form.Item>

                    <Form.Item
                        label="新密码"
                        name="newPassword"
                        rules={[{ required: true, message: '请输入你的新密码!' }]}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            width: '100%'
                        }}>
                            <Input.Password
                                onChange={checkPasswordMatch}
                                style={{
                                    width: 'calc(100% - 32px)',
                                    marginRight: '8px'
                                }}
                            />
                            <div style={{
                                width: '24px',
                                height: '32px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                flexShrink: 0
                            }}>
                                {/* 占位空间，保持布局一致 */}
                            </div>
                        </div>
                    </Form.Item>

                    <Form.Item
                        label="确认新密码"
                        name="confirmPassword"
                        dependencies={['newPassword']}
                        rules={[
                            { required: true, message: '请确认你的新密码!' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('newPassword') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error('两次输入的密码不匹配!'));
                                },
                            }),
                        ]}
                    >
                        <div style={{
                            display: 'flex',
                            alignItems: 'center',
                            width: '100%'
                        }}>
                            <Input.Password
                                onChange={checkPasswordMatch}
                                style={{
                                    width: 'calc(100% - 32px)',
                                    marginRight: '8px'
                                }}
                                placeholder="再次输入新密码"
                            />
                            <div style={{
                                width: '24px',
                                height: '32px',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                flexShrink: 0
                            }}>
                                {renderPasswordMatchIcon()}
                            </div>
                        </div>
                    </Form.Item>

                    <Form.Item>
                        <Button type="primary" htmlType="submit" loading={loading}>
                            {loading ? '修改中...' : '修改密码'}
                        </Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    );
};

export default SecuritySettings;